package edu.neu.springcloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import edu.neu.springcloud.entity.Commodity;
import edu.neu.springcloud.entity.Factory;
import edu.neu.springcloud.service.FactoryService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/factory")
public class FactoryController {

    @Autowired
    private FactoryService factoryService;

    @HystrixCommand(
            fallbackMethod = "listFactoryHystrix",  // 指定降级方法
            commandProperties = {
                // 10s内请求数大于多少个时就进行熔断判断，此处设定为了5，方便演示
                @HystrixProperty(name=HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD, value="5"),
                // 请求错误率大于百分之多少时就启动熔断，此处设定为了10%，方便演示
                @HystrixProperty(name=HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE, value="10"),
                // 熔断启动后多少秒后去尝试请求，单位毫秒，此处设定为了10秒（10000ms）方便演示
                @HystrixProperty(name= HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value="10000")})
    @GetMapping("/list")
    public List<Factory> listFactory(
            @RequestParam(value = "id", required = false) Long id,
            @RequestParam(value = "name", required = false) String name) {
        if ((id == null ? false : id < 1)){
            throw new RuntimeException("id非法");
        }
        return factoryService.list(id, name);
    }

    /**
     * listFactory的降级方法
     */
    public List<Factory> listFactoryHystrix(
            @RequestParam(value = "id", required = false) Long id,
            @RequestParam(value = "name", required = false) String name,
            Throwable throwable) {
//        throwable.printStackTrace();
        List<Factory> list = new ArrayList<>();
        list.add(new Factory().setName("出现错误，此服务已被降级处理-8011"));
        return list;
    }

    @PostMapping("/add")
    public boolean add(@RequestBody Factory factory) {
        return factoryService.add(factory);
    }

    @PostMapping("/update")
    public boolean update(@RequestBody Factory factory) {
        return factoryService.update(factory);
    }

    @GetMapping("/delete/{id}")
    public boolean delete(@PathVariable("id") Long id) {
        return factoryService.delete(id);
    }
}

